package com.instpower.things.handlers;

import com.instpower.things.config.Configs;
import com.instpower.things.instpower.Connection;
import com.instpower.things.instpower.DeviceSession;
import com.instpower.things.instpower.DeviceSessionManager;
import com.instpower.things.instpower.Handler;
import com.instpower.things.service.InstService;
import com.instpower.things.transport.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.time.LocalDateTime;
import java.time.ZoneId;

/**
 *
 * @ClassName Handler0902Action
 * @Author: hellmash@gmail.com
 * @Date: 2020/3/15
 * @Version: 1.0.0
 * @Description: 处理心跳
 *
 */
@Component(value = "CMD0902")
public class Handler0902Action extends Handler<Request> {

    @Value("${things.timeZone}")
    private String zoneId;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private InstService instService;

    @Override
    public short getId() {
        return Configs.BEAT;
    }

    @Override
    public void execute(Connection connection, Request data) throws UnsupportedEncodingException {
        String cabinetSn = data.getHeader().getAddr();
        logger.info("[{}]:Exec - CMD0902 - BEGIN",cabinetSn);
        //检测session,当前连接的connection是否已经发生变化
        if(!connection.getId().equals(DeviceSessionManager.getInstance().get(cabinetSn).getMConnection().getId())){
            DeviceSessionManager.getInstance().add(new DeviceSession(connection, cabinetSn));
        }
        try {
            //响应内容
            Response response = new Response();
            Header header = new Header();
            header.setPtrol(data.getHeader().getPtrol());
            header.setAddr(data.getHeader().getAddr());
            header.setCommand(data.getHeader().getCommand());

            LocalDateTime nowTime = LocalDateTime.now(ZoneId.of(zoneId));
            DataBuffer respData = new DataBuffer(9);
            respData.writeByte(0x01);
            respData.writeShort(nowTime.getYear());
            respData.writeByte(nowTime.getMonthValue());
            respData.writeByte(nowTime.getDayOfMonth());
            respData.writeByte(nowTime.getHour());
            respData.writeByte(nowTime.getMinute());
            respData.writeByte(nowTime.getSecond());
            respData.writeByte((byte) (nowTime.getDayOfWeek().getValue() - 1));

            header.setLength((short) (respData.readableBytes() + 2));
            response.setHeader(header);
            MTData mData = new MTData();
            mData.setDatas(respData.readByteArray(respData.readableBytes()));
            response.setData(mData);

            this.sendResponse(connection, response);

        } catch (Exception dex) {
            logger.error("机柜 {} 状态获取失败!",cabinetSn);
            logger.error(dex.getLocalizedMessage(),dex);
        }
        logger.info("[{}]:Exec - CMD0902 - END",cabinetSn);
    }
}
